<template>
  <ckeditor
    v-if="editor && config"
    v-model="editData"
    :editor="editor"
    :config="config"
    @ready="onEditorReady"
  />
</template>

<script setup>
import { computed, ref, onMounted, onBeforeUnmount, watch } from "vue";
import { Ckeditor } from "@ckeditor/ckeditor5-vue";

import {
  ClassicEditor,
  Alignment,
  AutoImage,
  AutoLink,
  Autosave,
  Bold,
  Emoji,
  Essentials,
  GeneralHtmlSupport,
  ImageBlock,
  ImageInsert,
  ImageInsertViaUrl,
  ImageToolbar,
  ImageUpload,
  Italic,
  Link,
  Mention,
  Paragraph,
  SimpleUploadAdapter,
  Strikethrough,
  Table,
	TableToolbar,
  Underline,
} from "ckeditor5";

import translations from "ckeditor5/translations/zh-cn.js";
import MathType from "@wiris/mathtype-ckeditor5/dist/index.js";
import mathml2latex from "mathml2latex";
import "ckeditor5/ckeditor5.css";

// Use GPL license key for open source projects
const LICENSE_KEY = "GPL";

const isLayoutReady = ref(false);

const editor = ClassicEditor;
const editorInstance = ref(null); // 存储编辑器实例
// 获取编辑器实例
const onEditorReady = (editor) => {
  editorInstance.value = editor;
};
const isDestroying = ref(false); // 添加销毁状态标志

// 转换内容为LaTeX
const convertContentToLatex = (html) => {
  try {
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, "text/html");
    const mathElements = doc.querySelectorAll("math");

    mathElements.forEach((mathEl) => {
      try {
        const mathML = mathEl.outerHTML;
        const latex = mathml2latex.convert(mathML);
        const latexNode = doc.createTextNode(`$${latex}$`);
        mathEl.replaceWith(latexNode);
      } catch (e) {
        console.error("公式转换失败", e);
      }
    });

    return doc.body.innerHTML;
  } catch (error) {
    console.error("内容转换异常", error);
    return html;
  }
};
const props = defineProps({
  value: String,
  modelValue: String,
});

defineExpose({ convertContentToLatex });
const config = computed(() => {
  if (!isLayoutReady.value) {
    return null;
  }

  return {
    toolbar: {
      items: [
        "bold",
        "italic",
        "underline",
        "strikethrough",
        "|",
        "alignment:left",
        "alignment:center",
        "alignment:right",
        "|",
        "link",
        "emoji",
        "insertImage",
        'insertTable',
        "|",
        "MathType",
      ],
      shouldNotGroupWhenFull: false,
    },
    plugins: [
      Alignment,
      AutoImage,
      AutoLink,
      Autosave,
      Bold,
      Emoji,
      Essentials,
      GeneralHtmlSupport,
      ImageBlock,
      ImageInsert,
      ImageInsertViaUrl,
      ImageToolbar,
      ImageUpload,
      Italic,
      Link,
      Mention,
      Paragraph,
      SimpleUploadAdapter,
      Strikethrough,
      Table,
			TableToolbar,
      Underline,
      MathType,
    ],
    htmlSupport: {
      allow: [
        {
          name: /^.*$/,
          styles: true,
          attributes: true,
          classes: true,
        },
      ],
    },
    image: {
      toolbar: [
        "imageStyle:inline",
        "imageStyle:block",
        "imageStyle:side",
        "|",
        "imageUpload", // 确保包含上传按钮
        "toggleImageCaption",
        "imageTextAlternative",
      ],
    },
    initialData: "",
    language: "zh-cn",
    licenseKey: LICENSE_KEY,
    link: {
      addTargetToExternalLinks: true,
      defaultProtocol: "https://",
      decorators: {
        toggleDownloadable: {
          mode: "manual",
          label: "Downloadable",
          attributes: {
            download: "file",
          },
        },
      },
    },
    mention: {
      feeds: [
        {
          marker: "@",
          feed: [
            /* See: https://ckeditor.com/docs/ckeditor5/latest/features/mentions.html */
          ],
        },
      ],
    },
    simpleUpload: {
      // Configuration.
      uploadUrl: "https://your-api.com/upload", // 必须配置上传端点
      withCredentials: true, // 如果需要cookie验证
      headers: {
        "X-CSRF-TOKEN": "your-csrf-token", // 安全头部
      },
    },
    placeholder: "在此输入内容",
    translations: [translations],
  };
});
const editData = computed({
  get() {
    return props.value || props.modelValue;
  },
  set(val) {
    emit("update:value", val);
  },
});
const emit = defineEmits(["update:value", "update:latex"]);
onMounted(() => {
  isLayoutReady.value = true;
});
// 组件销毁时清理资源
onBeforeUnmount(() => {
  // 设置销毁状态标志
  isDestroying.value = true;
  if (editorInstance.value) {
    try {
      // 1. 保存未提交的内容（如果有自动保存功能）
      if (editorInstance.value.plugins.has("Autosave")) {
        const autosave = editorInstance.value.plugins.get("Autosave");
        autosave.save();
      }

      // 2. 销毁编辑器实例
      editorInstance.value
        .destroy()
        .then(() => {
          editorInstance.value = null;
        })
        .catch((error) => {
          console.error("编辑器销毁失败:", error);
        });
    } catch (e) {
      console.error("销毁编辑器时发生错误:", e);
    }
  }
});
</script>
